package com.dexilaonian.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.R;
import com.dexilaonian.model.AddressPickTask;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.view.DatePickerPopWin;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import okhttp3.Call;

import static com.dexilaonian.R.id.rl_data;


public class EditActivity
        extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_topText)
    TextView baseTopText;
    @Bind(R.id.base_choose)
    TextView baseChoose;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.et_idCard)
    EditText etIdCard;
    @Bind(R.id.ivvv)
    ImageView ivvv;
    @Bind(R.id.date_doc)
    TextView dateDoc;

    @Bind(R.id.et_relation)
    EditText etRelation;
    @Bind(R.id.ivvv2)
    ImageView ivvv2;
    @Bind(R.id.tv_city_choose)
    TextView tvCityChoose;
    @Bind(R.id.et_edit_phone)
    EditText editPhone;
    @Bind(R.id.rl_city)
    RelativeLayout rlCity;

    @Bind(R.id.btn_shenqing)
    Button btnShenqing;
    @Bind(R.id.et_xiangxidizhi2)
    EditText etXiangxidizhi2;
    @Bind(R.id.et_medical_history2)
    EditText etMedicalHistory2;
    @Bind(R.id.ed_nan)
    TextView edNan;
    @Bind(R.id.ed_nv)
    TextView edNv;
    @Bind(R.id.rl_data)
    RelativeLayout rlData;

    private String countyStr;
    private String cityStr;
    private String provinceStr;
    private int startDay = 0;
    private String customerId;
    private String shengqing_url;
    private String shengqing_url2;
    private String myprovice;
    private String mycity;
    private String abs;
    private int gender =1 ;

    @Override
    public int getLayoutID() {
        return R.layout.activity_edit;
    }

    @Override
    public void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                String realName = extras.getString("realName");
                gender = extras.getInt("gender");
                long birthday = extras.getLong("birthday");
                String idcard = extras.getString("idcard");
                String medicalHistory = extras.getString("medicalHistory");
                String relation = extras.getString("relation");
                String phone = extras.getString("phone");
                String province = extras.getString("province");
                String city = extras.getString("city");
                String address = extras.getString("address");
                customerId = extras.getString("customerId");
                if (gender == 1) {
                    edNan.setBackground(getDrawable(R.drawable.xingbiexuanzezhuangtai));
                    edNv.setBackgroundColor(getColor(R.color.white));
                } else {
                    edNan.setBackgroundColor(getColor(R.color.white));
                    edNv.setBackground(getDrawable(R.drawable.xingbiexuanzezhuangtai));
                }
                if (!TextUtils.isEmpty(medicalHistory)) {
                    etMedicalHistory2.setText(medicalHistory);
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String format = simpleDateFormat.format(Long.parseLong(String.valueOf(birthday)));
                dateDoc.setText(format);
                if (!TextUtils.isEmpty(relation)) {
                    etRelation.setText(relation);
                }
                if (!TextUtils.isEmpty(idcard)) {
                    etIdCard.setText(idcard);
                }

                if (!TextUtils.isEmpty(realName)) {
                    etName.setText(realName);
                }
                if (!TextUtils.isEmpty(phone)) {
                    editPhone.setText(phone);
                }
                if (!TextUtils.isEmpty(province) && !TextUtils.isEmpty(city)) {
                    tvCityChoose.setText(province + " " + city);
                }
                if (!TextUtils.isEmpty(address)) {
                    etXiangxidizhi2.setText(address);
                }
            }
        }
        baseTopText.setText("申请服务对象");
    }

    @OnClick({R.id.date_doc, R.id.ed_nan, R.id.ed_nv,
            R.id.back,
            rl_data,
            R.id.rl_city,R.id.base_topText,
            R.id.btn_shenqing})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
            case R.id.base_topText:
                finish();
                break;
            case R.id.ed_nan:
                gender = 1;
                edNan.setBackground(getDrawable(R.drawable.xingbiexuanzezhuangtai));
                edNv.setBackgroundColor(getColor(R.color.white));
                break;
            case R.id.ed_nv:
                gender = 2;
                edNan.setBackgroundColor(getColor(R.color.white));
                edNv.setBackground(getDrawable(R.drawable.xingbiexuanzezhuangtai));
                break;
            case rl_data:
                initBirth();
                break;
            case R.id.rl_city:
                wheel();
                break;
            case R.id.btn_shenqing:
                String mEt_name = etName.getText().toString().trim();
                String mIdCard = etIdCard.getText().toString().trim();
                String mMedicalHistory = etMedicalHistory2.getText().toString().trim();
                String myPhone = editPhone.getText().toString().trim();
                String myTime = dateDoc.getText().toString().trim();
                String xiangxidizhi = etXiangxidizhi2.getText().toString().trim();
                String choose_address = tvCityChoose.getText().toString().trim();
                String relation = etRelation.getText().toString().trim();
                if (TextUtils.isEmpty(mEt_name)) {
                    showToast("请输入名字");
                    return;
                }
                if (TextUtils.isEmpty(mIdCard)) {
                    showToast("请输入身份证号码");
                    return;
                }

                if (TextUtils.isEmpty(myPhone)) {
                    showToast("请输入电话号码");
                    return;
                }
                if (myPhone.length() != 11) {
                    showToast("电话号码长度不正确");
                    return;
                }
                if (TextUtils.isEmpty(myTime)) {
                    showToast("请选择时间");
                    return;
                } else {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = formatter.parse(myTime);
                        long time = parse.getTime();
                        abs = String.valueOf(Math.abs(time));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (TextUtils.isEmpty(choose_address)) {
                    showToast("请选择地址");
                    return;
                } else {
                    String[] split = choose_address.split(" ");
                    myprovice = split[0];
                    mycity = split[1];
                }
                if (TextUtils.isEmpty(xiangxidizhi)) {
                    showToast("请填写详细地址");
                    return;
                }
                initShengqing(mEt_name, myPhone, gender + "", mIdCard, myprovice, mycity, xiangxidizhi, mMedicalHistory, relation, abs);

                break;
            case R.id.date_doc:
                initBirth();
                break;
        }
    }

    /**
     * 弹出选择器
     */
    private void wheel() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);

        task.setCallback(new AddressPickTask.Callback() {


            @Override
            public void onAddressInitFailed() {
                showToast("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                provinceStr = province.getAreaName();
                cityStr = city.getAreaName();
                countyStr = county.getAreaName();
                tvCityChoose.setText(provinceStr + " " + cityStr + " " + countyStr);
            }
        });
        task.execute("广东 ", "深圳 ", "福田");
    }

    private void initBirth() {

        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(EditActivity.this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                Logutil.e(dateDesc);
                dateDoc.setText(dateDesc);
            }
        }).textConfirm("确定") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                .minYear(1900) //min year in loop
                .maxYear(2550) // max year in loop
                .dateChose("2013-11-11") // date chose when init popwindow
                .build();
        pickerPopWin.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        pickerPopWin.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        pickerPopWin.showPopWin(EditActivity.this);
    }

    private void initShengqing(String mEt_name, String myPhone, String s, String mIdCard, String myprovice, String mycity,
                               String xiangxidizhi, String mMedicalHistory, final String relation, String abs) {
        showProgressBar(true);
        Map<String, String> map = new HashMap();
        map.put("realName", mEt_name);
        map.put("phone", myPhone);
        map.put("gender", s);
        map.put("IDCard", mIdCard);
        map.put("province", myprovice);
        map.put("city", mycity);
        map.put("address", xiangxidizhi);
        map.put("medicalHistory", mMedicalHistory);
        map.put("relation", relation);
        map.put("birthday", abs);
        if (TextUtils.isEmpty(customerId)) {
            shengqing_url = Constant.base_url + "/customer/save.do";
            Okhttp.postString(true, shengqing_url, map, new Okhttp.CallBac() {
                @Override
                public void onError(Call call, Exception e, String state, int id) {
                    showProgressBar(false);
                }
                @Override
                public void onResponse(String response, int id) {
                    showProgressBar(false);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int status = Integer.parseInt(jsonObject.optString("status"));
                        if (status == 34 || status == 16) {
                            startActivity(new Intent(EditActivity.this, LoginActivity.class));
                            return;
                        }
                        if (status == 0) {
                            Intent intent = new Intent(EditActivity.this, ServiceActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onNoNetwork(String state) {
                    showProgressBar(false);
                }
            });
        } else {
            shengqing_url2 = Constant.base_url + "/customer/edit.do";
            map.put("customerId", customerId);
            Okhttp.postString(true, shengqing_url2, map, new Okhttp.CallBac() {
                @Override
                public void onError(Call call, Exception e, String state, int id) {
                    showProgressBar(false);
                }
                @Override
                public void onResponse(String response, int id) {
                    showProgressBar(false);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int status = Integer.parseInt(jsonObject.optString("status"));
                        if (status == 34 || status == 16) {
                            startActivity(new Intent(EditActivity.this, LoginActivity.class));
                            return;
                        }
                        if (status == 0) {
                            Intent intent = new Intent(EditActivity.this, ServiceActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onNoNetwork(String state) {
                    showProgressBar(false);
                }
            });
        }
    }
}
